/*
该插件配合macro-filter-box.html，
不想将html写到脚本里
调用：$(el).filterBox({onsubmit:function(form, data)})
*/
;(function($){
	var data = {
		spec: false,
		team:[],
		job: []
	}
	
	var addTo = function(array, value){
		var exists= false;
		for(var i=0; i<array.length; i++){
			if(array[i]===value){
				exists = true;
				break;
			}
		}
		if(!exists)
		array.push(value);
	}
	
	var deleteFrom = function(array, value){
		var index = -1;
		for(var i=0; i<array.length; i++){
			if(array[i]===value){
				index= i;
				break;
			}
		}
		array.splice(index, 1);
	}
	
	var serialData = function(){
		return  "spec="+data.spec+"&team=" + data.team.toString()+"&job="+ data.job.toString(); 
	}
	
	$.fn.filterBox=function(options){
		var $form = $('.filter-box-form');
		
		var myoptions= $.extend({data: null, onsubmit: null, spec: false}, options);
		
		var $teamTree =  $('#id-filter-team-tree').treeview({
		        data: myoptions.data.teams,
		        showIcon: false,
		        showCheckbox: true,
		        showBorder: false,
		        selectedBackColor: 'transparent',
		        selectedColor: '#212529',
		        expandIcon: 'fa fa-caret-right',
		        collapseIcon: 'fa fa-caret-down',
		        checkedIcon: 'fa fa-check-square-o',
		        uncheckedIcon: 'fa fa-square-o',
		        onNodeChecked: function(event, node) {
		          addTo(data.team, node.href);
		        },
		        onNodeUnchecked: function (event, node) {
		          deleteFrom(data.team, node.href);
		        }
		});
		
		var $jobTree =  $('#id-filter-job-tree').treeview({
		        data: myoptions.data.jobs,
		        showIcon: false,
		        showCheckbox: true,
		        showBorder: false,
		        selectedBackColor: 'transparent',
		        selectedColor: '#212529',
		        expandIcon: 'fa fa-caret-right',
		        collapseIcon: 'fa fa-caret-down',
		        checkedIcon: 'fa fa-check-square-o',
		        uncheckedIcon: 'fa fa-square-o',
		        onNodeChecked: function(event, node) {
		          addTo(data.job, node.href);
		        },
		        onNodeUnchecked: function (event, node) {
		          deleteFrom(data.job, node.href);
		        }
		});
		
		$(".filter-box-form .treeview").click(function(k) {
		    k.stopPropagation();
		});
		
		$('.filter-box-selection-clear').click(function(){
			$teamTree.treeview("uncheckAll", {silent: true});
			$jobTree.treeview("uncheckAll", {silent: true});
		})

		$('.filter-box-selection-submit').click(function(){
			$('.filter-box').removeClass("show");
		    if(myoptions.onsubmit){
		    	myoptions.onsubmit($form, serialData());
		    }
		})
		
		return this;
	}
})(jQuery);